package dao.Category;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import model.Category;
import abstractFactory.Factory;

public class CategoryDAOJPA implements CategoryDAO{
	static EntityManager manager;

	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}

	public boolean save(Category category) {
		try	{
			getManager().getTransaction().begin();		
			getManager().persist(category);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean update(Category category){
		try{
			getManager().getTransaction().begin();
			getManager().merge(category);
			getManager().getTransaction().commit();
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public boolean delete(Category category){
		try {
			getManager().getTransaction().begin();
			Category c = getManager().find(Category.class,category.getId());
			getManager().remove(c);
			getManager().getTransaction().commit();			
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public List<Category> getAllCategories(){
		Query query = (Query) getManager().createQuery("SELECT c FROM Category c where c.active = 1" );
		@SuppressWarnings("unchecked")
		List<Category> category =  query.getResultList();
		return category;
	}

	public Long getTotalCategory(){
		Query query = (Query) getManager().createQuery("SELECT count(c) FROM Category c where c.active = 1" );
		Long total = (Long) query.getSingleResult();
		return total;
	}

	public Category getCategoryById(int categoryId)	{
		try {
			Category category = getManager().find(Category.class, categoryId);
			return category;
		} catch (Exception e) {
			return null;				
		}
	}
}
